/**
 * 系统管理 用户管理
 */
<template>
    <div>
        <!-- 面包屑导航 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>用户管理</el-breadcrumb-item>
        </el-breadcrumb>
        <!-- 搜索筛选 -->
        <el-form :inline="true" :model="formInline" class="user-search">
        <el-form-item label="搜索：">
            <el-select size="small" v-model="formInline.isLock" placeholder="请选择">
            <el-option label="全部" value=""></el-option>
            <el-option label="正常" value="N"></el-option>
            <el-option label="已锁定" value="Y"></el-option>
            </el-select>
        </el-form-item>
        <el-form-item label="">
            <el-input size="small" v-model="formInline.userName" placeholder="输入用户名"></el-input>
        </el-form-item>
        <el-form-item label="">
            <el-input size="small" v-model="formInline.userMobile" placeholder="输入手机号"></el-input>
        </el-form-item>
        <el-form-item>
            <el-button size="small" type="primary" icon="el-icon-search" @click="search">搜索</el-button>
        </el-form-item>
        </el-form>
        <!--列表-->
        <el-table size="small" @selection-change="selectChange" :data="userData" highlight-current-row v-loading="loading" border element-loading-text="拼命加载中" style="width: 100%;">
        <el-table-column align="center" type="selection" width="50">
        </el-table-column>
        <el-table-column align="center" sortable prop="uname" label="用户名" width="90">
        </el-table-column>
        <el-table-column align="center" sortable prop="profile" label="头像" width="100">
            <template slot-scope="scope">
            <img :src="scope.row.profile" alt="" class="profile">
            </template>       
        </el-table-column>
        <el-table-column align="center" sortable prop="create_time" label="注册时间" width="120">
        </el-table-column>
        <el-table-column align="center" sortable prop="tel" label="电话" width="120">
        </el-table-column>
        <el-table-column align="center" sortable prop="mail" label="邮箱" min-width="130">
        </el-table-column>
        <el-table-column align="center" sortable prop="local" label="地址" min-width="250">
        </el-table-column>
        <el-table-column align="center" sortable prop="gender" label="性别" min-width="60">
        </el-table-column>
        <el-table-column align="center" sortable prop="birthday" label="年龄" min-width="100">
        </el-table-column>
        <el-table-column align="center" sortable prop="state" label="状态" min-width="100">
            <template slot-scope="scope">
            <el-switch v-model="scope.row.state" active-color="#13ce66" inactive-color="#ff4949" @change="editType(scope.$index, scope.row)">
            </el-switch>
            </template>
        </el-table-column>
        <el-table-column label="操作" min-width="150">
            <template slot-scope="scope">
            <el-button size="mini" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
            <el-button size="mini" type="danger" @click="deleteUser(scope.$index, scope.row)">删除</el-button>
            </template>
        </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <Pagination v-bind:child-msg="pageparm" @callFather="callFather"></Pagination>
        <!-- 编辑界面 -->
        <el-dialog :title="title" :visible.sync="editFormVisible" width="30%" @click='closeDialog("edit")'>
        <el-form label-width="80px" ref="editForm" :model="editForm" :rules="rules">
            <el-form-item label="用户名" prop="uname">
            <el-input size="small" v-model="editForm.uname" auto-complete="off" placeholder="请输入用户名"></el-input>
            </el-form-item>
            <el-form-item label="头像" prop="profile">
            <el-upload
                class="avatar-uploader"
                action="/adopt/image"
                :show-file-list="false"
                :http-request="upLoad"
                >
                <img v-if="editForm.profile" :src="editForm.profile" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
            </el-form-item>
            <el-form-item label="电话" prop="tel">
            <el-input size="small" v-model="editForm.tel" placeholder="请输入手机号"></el-input>
            </el-form-item>
            <el-form-item label="邮箱" prop="mail">
            <el-input size="small" v-model="editForm.mail" placeholder="请输入邮箱地址"></el-input>
            </el-form-item>
            <el-form-item label="性别" prop="gender">
            <el-radio v-model="editForm.gender" label="男">男</el-radio>
            <el-radio v-model="editForm.gender" label="女">女</el-radio>
            </el-form-item>
            <el-form-item label="生日" prop="birthday">
            <el-input size="small" v-model="editForm.birthday" placeholder="请使用正确格式修改生日"></el-input>
            </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
            <el-button size="small" @click='closeDialog("edit")'>取消</el-button>
            <el-button size="small" type="primary" :loading="loading" class="title" @click="submitForm('edit')">保存</el-button>
        </div>
        </el-dialog>
    </div>
</template>

<script>
import { getuserInfo,updateUserInfo,deleteUser,userLock } from '@/api/userApi.js'
import { uploadImg } from '@/api/api.js'
import {
  userExpireToken,
} from '../../api/userMG'
import Pagination from '../../components/Pagination'
export default {
    data() {
        return {
        fshow: '', //switch
        loading: false, //是显示加载
        title: '添加用户',
        editFormVisible: false, //控制编辑页面显示与隐藏
        dataAccessshow: false, //控制数据权限显示与隐藏
        unitAccessshow: false, //控制所属单位隐藏与显示
        // 编辑与添加
        editForm: {
            uname: '',
            profile: '',
            create_time: '',
            tel: '',
            mail: '',
            local: '',
            gender: '',
            age: '',
            token: localStorage.getItem('logintoken')
        },
        // 选择数据
        selectdata: [],
        // rules表单验证
        rules: {
            userName: [
            { required: true, message: '请输入用户名', trigger: 'blur' }
            ],
            userRealName: [
            { required: true, message: '请输入姓名', trigger: 'blur' }
            ],
            roleId: [{ required: true, message: '请选择角色', trigger: 'blur' }],
            userMobile: [
            { required: true, message: '请输入手机号', trigger: 'blur' },
            {
                pattern: /^1(3\d|47|5((?!4)\d)|7(0|1|[6-8])|8\d)\d{8,8}$/,
                required: true,
                message: '请输入正确的手机号',
                trigger: 'blur'
            }
            ],
            userEmail: [
            { required: true, message: '请输入邮箱', trigger: 'blur' },
            {
                pattern: /^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/,
                required: true,
                message: '请输入正确的邮箱',
                trigger: 'blur'
            }
            ],
            userSex: [{ required: true, message: '请选择性别', trigger: 'blur' }]
        },
        // 删除用户
        seletedata: {
            ids: '',
            token: localStorage.getItem('logintoken')
        },
        // 重置密码
        resetpsd: {
            userId: '',
            token: localStorage.getItem('logintoken')
        },
        // 用户下线
        offline: {
            token: localStorage.getItem('logintoken')
        },
        // 请求数据参数
        formInline: {
            page: 1,
            limit: 10,
            deptId: '',
            userName: '',
            userMobile: '',
            isLock: ''
        },
        //用户数据
        userData: [],
        // 数据权限
        UserDept: [],
        defaultProps: {
            children: 'children',
            label: 'name'
        },
        // 选中
        checkmenu: [],
        //参数role
        saveroleId: '',
        // 分页参数
        pageparm: {
            currentPage: 1,
            pageSize: 10,
            total: 10
        },
        }
    },
    // 注册组件
    components: {
        Pagination
    },
    created() {
        this.getdata()
    },

    /**
     * 里面的方法只有被调用才会执行
     */
    methods: {
        async upLoad(file){
        let formDatas = new FormData()
            formDatas.append('file', file.file)
                try {
                await uploadImg(formDatas)         
                } catch (error) {
                    this.editForm.profile = error.url;
                }
        },
        //转换时间戳
        date(time) {
                var date = new Date(time);
                var y = date.getFullYear();
                var m = date.getMonth() + 1;
                var d = date.getDate();
                m = m > 9 ? m : '0' + m;
                return y + '-' + m + '-' + d
            },
        // 获取数据方法
        async getdata() {
        this.loading = true
        const { data } = await getuserInfo()
        this.loading = false
        this.userData = data
        // if(!this.userData.state){
        //   this.fshow = true
        // }else if(this.userData.state){
        //   this.fshow = false
        // }
        // 分页赋值
        this.pageparm.currentPage = this.formInline.page
        this.pageparm.pageSize = this.formInline.limit
        this.pageparm.total = data.length
        // 模拟数据结束

        },
        // 分页插件事件
        callFather(parm) {
        this.formInline.page = parm.currentPage
        this.formInline.limit = parm.pageSize
        this.getdata(this.formInline)
        },
        //搜索事件
        search() {
        this.getdata(this.formInline)
        },
        // 修改type
        async editType(index, row) {
        this.loading = true
        let params = {
            state:'',
            mail:''
        }
        params.mail = row.mail
        params.state = row.state
        console.log(row.state)
        await userLock(params).then(res => {
            this.loading = false
            console.log(res)
            if (res.success == false) {
            this.$message({
                type: 'info',
                message: res.message
            })
            } else {
            this.$message({
                type: 'success',
                message: '状态修改成功'
            })
            }
        })
        },
        //显示编辑界面
        handleEdit: function(index, row) {
        console.log(row)
        this.editFormVisible = true
        if (row != undefined && row != 'undefined') {
            this.title = '修改用户'
            this.editForm.uname = row.uname
            this.editForm.profile = row.profile
            this.editForm.create_time = row.create_time
            this.editForm.tel = row.tel
            this.editForm.mail = row.mail
            this.editForm.local = row.local
            this.editForm.gender = row.gender
            this.editForm.age = row.age
            this.editForm.birthday = row.birthday
        } else {
            this.title = '添加用户'
            this.editForm.uname = ''
            this.editForm.profile = ''
            this.editForm.create_time = ''
            this.editForm.tel = ''
            this.editForm.mail = ''
            this.editForm.local = ''
            this.editForm.gender = ''
            this.editForm.age = ''
        }
        },
        // 编辑、添加提交方法
        async submitForm(dialog) {
            // 请求方法
            const { success } = await updateUserInfo(this.editForm)
            if(success) {
                this.getdata()
                this.closeDialog(dialog)
            }
        },
        //删除
        deleteUser(index,user) {
        this.$confirm('确认删除此用户吗?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
            }).then(async() => {
            const { success } = await deleteUser({'mail':user.mail})
            if(success) {
                this.getdata()
            }
            this.$message({
                type: 'success',
                message: '删除成功!'
            });
            }).catch(() => {
            this.$message({
                type: 'info',
                message: '已取消删除'
            });          
            });     
        },
        // 选择复选框事件
        selectChange(val) {
        this.selectdata = val
        },
        // 关闭编辑、增加弹出框
        closeDialog(dialog) {
        if (dialog == 'edit') {
            this.editFormVisible = false
        } else if (dialog == 'perm') {
            this.dataAccessshow = false
        } else if (dialog == 'unit') {
            this.unitAccessshow = false
        }
        },
        beforeAvatarUpload(file) {
            const isJPG = file.type === 'image/jpeg';
            const isLt2M = file.size / 1024 / 1024 < 2;

            if (!isJPG) {
            this.$message.error('上传头像图片只能是 JPG 格式!');
            }
            if (!isLt2M) {
            this.$message.error('上传头像图片大小不能超过 2MB!');
            }
            return isJPG && isLt2M;
        },


        // 下线用户
        offlineUser(index, row) {
        this.$confirm('确定要让' + row.userName + '用户下线吗?', '信息', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        })
            .then(() => {
            userExpireToken(row.userName)
                .then(res => {
                if (res.success) {
                    this.$message({
                    type: 'success',
                    message: '用户' + row.userName + '强制下线成功！'
                    })
                    this.getdata(this.formInline)
                } else {
                    this.$message({
                    type: 'info',
                    message: res.msg
                    })
                }
                })
                .catch(err => {
                this.loading = false
                this.$message.error('用户下线失败，请稍后再试！')
                })
            })
            .catch(() => {
            this.$message({
                type: 'info',
                message: '已取消'
            })
            })
        },
    
    }
}
</script>

<style scoped>
.user-search {
  margin-top: 20px;
}
.userRole {
  width: 100%;
}
.profile{
  width: 60px;
  height: auto;
}
 .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 60px;
    height: 60px;
    line-height: 60px;
    text-align: center;
    border:1px dashed #b4bccc;
  }
  .avatar {
    width: 60px;
    height: auto;
    display: block;
  }
</style>

 